<template>
  <!-- 物流下单 -->
  <a-modal :width="1200" v-model:visible="showFbaLogistics" title="物流下单" top="8vh" title-align="start" :on-before-ok="submitData" :ok-loading="submitLoading" :mask-closable="false" @cancel="closedDialog">
    <a-tabs v-model:active-key="logisticType">
      <a-tab-pane :key="1" title="API对接的物流商">
        <div class="flex-c-sb logistic-w">
          <a-form ref="apiFormRef" style="width: 900px" :model="apiInfo" :rules="rules">
            <a-row :gutter="10">
              <a-col :span="9">
                <a-form-item field="logistic.id" label="物流渠道：" label-col-flex="100px">
                  <a-select v-model="apiInfo.logistic" @change="getChannel" placeholder="物流商" value-key="id" allow-search>
                    <a-option v-for="item of apiExpressProvider" :key="item.id" :label="item.expressName" :value="item" />
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item field="channel.id" hide-label>
                  <a-select v-model="apiInfo.channel" value-key="id" placeholder="物流渠道" allow-search>
                    <a-option v-for="item of apiChannelList" :key="item.id" :label="item.name" :value="item" />
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="9">
                <a-form-item field="address.id" label="发货地址：" label-col-flex="100px">
                  <a-select v-model="apiInfo.address" placeholder="发货地址" allow-search value-key="id">
                    <a-option v-for="item of addressList" :key="item.id" :label="item.name" :value="item" />
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
          <a-button type="primary">估算费用</a-button>
        </div>
      </a-tab-pane>
      <a-tab-pane :key="2" title="自定义物流商">
        <div class="logistic-w">
          <a-form ref="customFormRef" style="width: 900px" :model="customInfo" :rules="rules">
            <a-row :gutter="10">
              <a-col :span="9">
                <a-form-item field="logistic.id" label="物流渠道：" label-col-flex="100px">
                  <a-select v-model="customInfo.logistic" @change="getCustomChannel" placeholder="物流商" value-key="id" allow-search>
                    <a-option v-for="item of customExpressProvider" :key="item.id" :label="item.expressName" :value="item" />
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item field="channel.id" hide-label>
                  <a-select v-model="customInfo.channel" value-key="id" placeholder="物流渠道" allow-search>
                    <a-option v-for="item of customChannelList" :key="item.id" :label="item.name" :value="item" />
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </a-tab-pane>
    </a-tabs>
    <div class="table-title" style="margin-bottom: 10px">
      <span>合计 {{ fbaOrders.length }} 条 </span>
      <span v-if="logisticType == 1" style="margin-left: 10px">请完善物流交运的必要信息，点击编辑图标完善信息</span>
      <a-button v-if="logisticType == 1" type="primary" size="small" style="margin-left: 10px" @click="openDeclareInfo(fbaOrders)">批量设置报关信息</a-button>
    </div>
    <a-table
      class="table-two-line"
      ref="tableRef"
      row-key="id"
      :data="fbaOrders"
      :scroll="{
        y: 'calc(84vh - 300px)',
        x: '100%',
      }"
      size="mini"
      :pagination="false"
      :bordered="{ headerCell: true }"
    >
      <template #columns>
        <a-table-column data-index="sort" title="序号" :width="45" fixed="left">
          <template #cell="{ rowIndex }">
            <p>{{ rowIndex + 1 }}</p>
          </template>
        </a-table-column>
        <a-table-column title="店铺" :width="100" fixed="left">
          <template #cell="{ record }">
            <TextLimit>{{ record.shopName }}</TextLimit>
          </template>
        </a-table-column>
        <a-table-column title="发货单号/货件号" :width="120" fixed="left">
          <template #cell="{ record }">
            <p class="highlight">{{ record.billNo }}</p>
            <p class="highlight">{{ record.shipmentId || '-' }}</p>
          </template>
        </a-table-column>
        <a-table-column title="提交处理时间" :width="130">
          <template #cell="{ record }">
            <p>{{ $setTime(record.gmtSubmit, 'YYYY/MM/DD HH:mm') }}</p>
          </template>
        </a-table-column>
        <a-table-column data-index="warehouseName" title="发货仓" :width="100" />
        <a-table-column data-index="centerId" title="CenterId" :width="80" />
        <a-table-column title="国家" :width="80">
          <template #cell="{ record }">
            <p>{{ $extract(marketPlaceList[record.marketplaceId], 'name') }}-{{ $extract(marketPlaceList[record.marketplaceId], 'code') }}</p>
          </template>
        </a-table-column>
        <a-table-column title="省州/城市" :width="100">
          <template #cell="{ record }">
            <p>{{ $extract(record, 'shipToAddress.stateOrProvinceCode') || '--' }}</p>
            <p>{{ $extract(record, 'shipToAddress.city') || '--' }}</p>
          </template>
        </a-table-column>

        <a-table-column title="装箱数" :width="70">
          <template #cell="{ record }">
            <p>{{ record.boxDetails.length }}</p>
          </template>
        </a-table-column>
        <a-table-column title="重量(kg/lb)" :width="100">
          <template #cell="{ record }">
            <p>{{ getWeight(record.boxDetails, 'weight') }}</p>
            <p>{{ getWeight(record.boxDetails, 'weight2') }}</p>
          </template>
        </a-table-column>
        <template v-if="logisticType == 1">
          <a-table-column title="预估运费" :width="80">
            <template #cell>
              <p>--</p>
            </template>
          </a-table-column>
          <a-table-column title="报关信息" :width="70">
            <template #cell="{ record }">
              <p :class="{ highlight: !isSetDeclare(record.skuDetails), cursor: true }">
                <i class="icon icon-wendang" @click="openDeclareInfo([record])"></i>
              </p>
            </template>
          </a-table-column>
        </template>
        <template v-else>
          <a-table-column :width="130">
            <template #title>
              <span class="warningColor">*</span>
              <span>预估运费</span>
            </template>
            <template #cell="{ record, rowIndex }">
              <div class="cell flex-c">
                <span>￥</span>
                <a-input-number style="width: 90px" v-model="record.shipFee" />
                <icon-double-down v-if="rowIndex < fbaOrders.length - 1" class="edit-icon" @click="setGlobal(record, 'shipFee', rowIndex)" />
              </div>
            </template>
          </a-table-column>
          <a-table-column :width="120">
            <template #title>
              <span class="warningColor">*</span>
              <span>运单号</span>
            </template>
            <template #cell="{ record }">
              <a-input v-model="record.logisticsWaybillNumber" />
            </template>
          </a-table-column>
          <a-table-column :width="120">
            <template #title>
              <span class="warningColor">*</span>
              <span>跟踪号</span>
            </template>
            <template #cell="{ record }">
              <a-input v-model="record.logisticsTrackNumber" />
            </template>
          </a-table-column>
          <a-table-column :width="200" title="物流面单">
            <template #cell="{ record, rowIndex }">
              <p v-if="record.logisticsManifest">{{ record.logisticsManifest }}</p>
              <a-upload action="/" :custom-request="uplaodFest" :show-file-list="false">
                <template #upload-button>
                  <a-button size="mini" @click="currentIndex = rowIndex">
                    <template #icon>
                      <icon-upload />
                    </template>
                    <template #default>上传面单</template>
                  </a-button>
                </template>
              </a-upload>
            </template>
          </a-table-column>
        </template>
        <a-table-column title="操作" :width="70" fixed="right">
          <template #cell="{ rowIndex }">
            <a-popconfirm v-if="fbaOrders.length > 1" content="确定是否移除?" @ok="fbaOrders.splice(rowIndex, 1)" type="error">
              <a-button type="text">移除</a-button>
            </a-popconfirm>
          </template>
        </a-table-column>
      </template>
    </a-table>
  </a-modal>
  <!-- 设置报关信息 -->
  <FbaDeclare v-if="showFbaDeclare" :isShow="showFbaDeclare" :list="currentRows" @closed="showFbaDeclare = false" @success="getFbaListById(fbaOrders)" />
</template>
<script lang="ts" setup>
  import { ref, onMounted, PropType } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { findFbaShipmentPageByStore, placeFbaShipmentLogisticsByStore } from '@/api/purchase'
  import { marketPlaceList } from '@/utils/globalData'
  import FbaDeclare from './fbaDeclare.vue'
  import { listExpressProvider, pageExpressChannel, pageExpressAddress } from '@/api/warehouse'
  import { upload } from '@/api/base'

  onMounted(async () => {
    getFbaListById(props.list)
    getProvider()
    getAddress()
  })
  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    list: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
  })
  const showFbaLogistics = ref(props.isShow)
  const fbaOrders = ref<Array<any>>([])
  const submitLoading = ref(false)
  const apiInfo = ref<any>({})
  const customInfo = ref<any>({})
  const logisticType = ref(1)
  const currentRows = ref<Array<any>>([])
  const addressList = ref<Array<any>>([])
  const showFbaDeclare = ref(false)
  const apiExpressProvider = ref<Array<any>>([])
  const apiChannelList = ref<Array<any>>([])
  const customExpressProvider = ref<Array<any>>([])
  const customChannelList = ref<Array<any>>([])
  const apiFormRef = ref()
  const currentIndex = ref(0)
  const customFormRef = ref()
  const rules = ref({
    'logistic.id': [{ required: true, message: '请选择物流商' }],
    'channel.id': [{ required: true, message: '请选择物流渠道' }],
    'address.id': [{ required: true, message: '请选择发货地址' }],
  })

  // 初始化数据
  async function getFbaListById(list: Array<any>) {
    let ids = list.map((el: any) => el.id)
    const res: any = await findFbaShipmentPageByStore({
      ids: ids?.join(','),
      pageSize: 100,
      pageNum: 1,
    })
    fbaOrders.value = res?.data?.records || []
  }
  //显示重量
  function getWeight(boxDetails: any, key: string) {
    if (!boxDetails.length) return
    let num = 0
    boxDetails.forEach((el: any) => {
      num += Number(el[key] || 0)
    })
    return num
  }
  // 判断是否设置报关信息
  function isSetDeclare(skuDetails: any) {
    return skuDetails?.[0]?.declareName ? true : false
  }
  // 获取物流商
  async function getProvider() {
    const res: any = await listExpressProvider()
    let list = res?.data || []
    apiExpressProvider.value = list.filter((e: any) => e.providerType == 'api')
    customExpressProvider.value = list.filter((e: any) => e.providerType == 'custom')
  }
  // 根据物流商获取物流渠道-api
  async function getChannel() {
    apiChannelList.value = []
    if (!apiInfo.value.logistic?.id) return
    const res: any = await pageExpressChannel({
      expressProviderId: apiInfo.value.logistic?.id,
      pageNum: 1,
      pageSize: 9999,
    })
    let list = res?.data?.records || []
    apiChannelList.value = list.filter((el: any) => el.enable)
  }
  // 根据物流商获取物流渠道-自定义
  async function getCustomChannel() {
    customChannelList.value = []
    if (!customInfo.value.logistic?.id) return
    const res: any = await pageExpressChannel({
      expressProviderId: customInfo.value.logistic?.id,
      pageNum: 1,
      pageSize: 9999,
    })
    let list = res?.data?.records || []
    customChannelList.value = list.filter((el: any) => el.enable)
  }

  // 获取发货地址
  async function getAddress() {
    const res = await pageExpressAddress({
      pageNum: 1,
      pageSize: 9999,
    })
    let arr = res?.data?.records || []
    addressList.value = arr.filter((e: any) => e.type == 'ship')
  }

  // 关闭
  function closedDialog() {
    showFbaLogistics.value = false
    emit('closed')
  }

  // 打开设置报关信息
  function openDeclareInfo(list?: any) {
    currentRows.value = list
    showFbaDeclare.value = true
  }
  //设置全局
  function setGlobal(item: any, key: string, i: number) {
    fbaOrders.value.forEach((el: any, index: number) => {
      if (index > i) {
        el[key] = item[key]
      }
    })
  }
  // 上传附件
  async function uplaodFest(options: any) {
    let { fileItem } = options
    let formData = new FormData()
    formData.append('file', fileItem.file)
    const res: any = await upload(formData)
    if (res?.data?.publicUrl) {
      fbaOrders.value[currentIndex.value].logisticsManifest = res.data.publicUrl
    }
  }
  // 校验必填信息
  async function validateData() {
    let el = logisticType.value == 1 ? apiFormRef.value : customFormRef.value
    let valid = await el.validate((valid: any) => {
      return valid
    })
    if (valid) return false
    let flag = true
    if (logisticType.value == 2) {
      fbaOrders.value.forEach((el: any) => {
        if (!el.logisticsWaybillNumber || !el.logisticsTrackNumber || !(el.shipFee || el.shipFee === 0)) {
          flag = false
        }
      })
    }
    if (!flag) {
      Message.error('运费，运单号，跟踪号必填')
      return false
    }
    return true
  }
  // 保存
  async function submitData() {
    if (!(await validateData())) return false
    let list: Array<any> = []
    let formInfo = logisticType.value == 1 ? apiInfo.value : customInfo.value
    let feedConfigList = formInfo.channel.feedConfigList?.find((el: any) => el.shopType == 'Amazon')
    fbaOrders.value.forEach((el: any) => {
      let obj = {
        id: el.id,
        logisticType: logisticType.value,
        logisticId: formInfo.logistic?.id,
        logisticName: formInfo.logistic?.expressName,
        logisticCode: formInfo.logistic?.providerCode,
        logisticChannelId: formInfo.channel?.id,
        logisticChannelName: formInfo.channel?.name,
        logisticChannelCode: formInfo.channel?.code,
        shippingAddressId: formInfo.address?.id,
        logisticsManifest: el.logisticsManifest,
        logisticsTrackNumber: el.logisticsTrackNumber,
        logisticsWaybillNumber: el.logisticsWaybillNumber,
        shipFee: el.shipFee,
        carrierName: feedConfigList?.carrier,
        skuDetails: el.skuDetails,
      }
      list.push(obj)
    })
    let res: any = await placeFbaShipmentLogisticsByStore({
      placeLogisticsItems: list,
    })
    if (!res) return false
    Message.success('保存成功')
    emit('success')
    closedDialog()
  }
</script>
<style lang="less" scoped>
  .logistic-w {
    margin: 10px 0;
    border: 1px solid #ddd;
    padding: 10px;
    .arco-form-item {
      margin-bottom: 0;
    }
  }
</style>
